<template>
    <div class="page user-charge-view">
        <wv-header title="充值" fixed>
            <div class="btn-back" slot="left">
                <i class="iconfont iot-back" @click="$router.go(-1)"></i>
            </div>
            <div class="btn-back" slot="right">
                <span  @click="$router.push({ name: 'order-charge-list' })">充值记录</span>
            </div>
        </wv-header>

        <div class="main-header-fixed">
            <wv-group title="选择充值金额" class="charge-list" >
                <wv-grid>
                    <wv-grid-item @click="handleSelectMoney(money.money)" :key="money.money" :value="money.money"  :class="{ active: money.money == selectedMoney }" v-for="money in moneys">
                        <div class="money-value">{{ money.money }} 元</div>
                        <div v-if="money.score > 0" class="score-value">赠送{{ money.score }}积分</div>
                    </wv-grid-item>
                </wv-grid>
            </wv-group>
            <wv-radio class="pay-modes" title="支付方式" v-model="payMode" :options.sync="payModes"></wv-radio>
        </div>

        <div class="charge-btn">
            <wv-button type="primary" @click="handleCharge">充值</wv-button>
        </div>
    </div>
</template>

<script>
    import { mapState } from 'vuex';
    import util from '@/libs/util';

    export default {

        data () {
            return {
                moneys: [10, 20, 50, 100, 150, 200],
                moneys: [
                    { money: 10, score: 0 },
                    { money: 20, score: 0 },
                    { money: 50, score: 0 },
                    { money: 100, score: 0 },
                    { money: 150, score: 0 },
                    { money: 200, score: 0 },
                ],
                selectedMoney: 0,
                payMode: 'wxpay',
                payModes: [
                ]
            }
        },

        computed: {
            ...mapState({
                user: state => state.user.user
            })
        },

        created () {
            if (util.isWeixinBrowser()) {
                this.payMode = 'wxpay';
                this.payModes.push({
                    label: '微信支付',
                    value: 'wxpay'
                });
            } else {
                this.payMode = 'alipay';
                this.payModes.push({
                    label: '支付宝',
                    value: 'alipay'
                });
            }

            util.api().get('/api/orders/charges/config/moneys').then((resp) => {
                this.moneys = resp.data.data;
            });
        },

        mounted () {
            var paymodes = document.querySelectorAll('.pay-modes>.weui-cells>.weui-cell>.weui-cell__bd');
            if (paymodes && paymodes.length > 0) {
                paymodes.forEach(node => {
                    if (node.children[0].innerText == '支付宝') {
                        node.children[0].className = 'alipay';
                    } else if (node.children[0].innerText == '微信支付') {
                        node.children[0].className = 'wxpay';
                    }
                });
            }
        },

        methods: {
            handleSelectMoney (money) {
                this.selectedMoney = money;
            },

            handleCharge () {

                let data = {money: this.selectedMoney, pay_mode: this.payMode, source: 'wap'};
                if (window.wechat_user && window.wechat_user.hasOwnProperty('id')) {
                    data.openid = window.wechat_user.id;
                }
                if (this.validator(data)) {
                    this.$root.loading('充值中');

                    util.api().post('/api/orders/charge/create', data).then((resp) => {
                        this.$root.closeLoading();
                        if (resp.data.status == true) {
                            if (this.payMode == 'alipay') {
                                window.location.href = resp.data.data.pay_config;
                            } else {
                                this.runWxpay(resp.data.data.pay_config);
                            }
                        } else {
                            this.$root.error(resp.data.message);
                        }
                    }).catch((e) => {
                        this.$root.closeLoading();
                        util.handleApiException(e, this, '充值失败');
                    });
                }
            },

            validator (data) {
                if (data.money <= 0) {
                    this.$root.error('请选择充值金额');
                    return false;
                }

                return true;
            },

            runWxpay (params) {
                const that = this
                const onBridgeReady = () => {
                    WeixinJSBridge.invoke('getBrandWCPayRequest', params, (result) => {
                        if (result.err_msg === 'get_brand_wcpay_request:ok') {
                            that.$root.success('微信支付成功');
                            that.$router.push({ name: 'order-charge-list' });
                        }

                        if (result.err_msg === 'get_brand_wcpay_request:cancel') {
                            that.$root.toast('您已经取消了微信支付')
                        }

                        if (result.err_msg === 'get_brand_wcpay_request:fail') {
                            that.$root.error('微信支付失败')
                        }
                    })
                };

                if (typeof WeixinJSBridge === 'undefined') {
                    if (document.addEventListener) {
                        document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false)
                    } else if (document.attachEvent) {
                        document.attachEvent('WeixinJSBridgeReady', onBridgeReady)
                        document.attachEvent('onWeixinJSBridgeReady', onBridgeReady)
                    }
                } else {
                    onBridgeReady()
                }
            }
        }
    }
</script>